import os
import re
import shutil
import common.gyblog as log
import manage_db.query_db as q

LOG = log.get_logger()

# 查询条件，空表示全查询
# SERIES = '1pondo'
SERIES = '1pondo'
YEAR = '2022'
# 比较路径
PATH = '\\\\lcnas\\xishu16t2020_1\无遮挡机动车\\1pondo\\{}\\'.format(YEAR)


def compare_db_and_dir(series, year):
    query_db = q.query_by_series_and_year(series, year)
    list_db = []
    for q_db in query_db:
        list_db.append(q_db['num'])
    root_dirs = os.listdir(PATH)
    list_dir = []
    for dir in root_dirs:
        print(dir)
        num = re.search("\d{6}_\d{3}", dir).group()
        if num[4:6] == YEAR[2:]:
            list_dir.append(num)
    diff_1 = set(list_db) - set(list_dir)
    diff_2 = set(list_dir) - set(list_db)
    print('数据库中有{}个，目录中有{}个'.format(len(set(list_db)), len(set(list_dir))))
    print('db中有，但是数据库中没有（未下载）：', diff_1)
    print('数据库中有，但是db中没有（放错位置）：', diff_2)


def sort_movies_by_year(series):
    path = '\\\\lcnas\\xishu16t2020_1\\无遮挡机动车temp\\{}\\'.format(series)
    goal_path = '\\\\lcnas\\xishu16t2020_1\\无遮挡机动车\\{}\\'.format(series)
    root_dirs = os.listdir(path)
    for root_dir in root_dirs:
        num = re.search("\d{6}-\d{3}", root_dir).group()
        year = '20' + num[4:6]
        if not os.path.exists(goal_path + year):
            os.mkdir(goal_path + year)
            LOG.info('创建文件夹成功：'.format(goal_path + year))
        # 遍历子文件夹
        dirs = os.listdir(path + root_dir)
        for dir in dirs:
            if dir[-4:] != '.nfo':
                old_path = path + root_dir + '\\' + dir
                new_path = goal_path + year + '\\' + dir
                try:
                    shutil.move(old_path, new_path)
                    print(old_path, new_path)
                    LOG.info('移动文件：{},{}'.format(old_path, new_path))
                except FileExistsError as e:
                    print(repr(e))
                    LOG.error(repr(e))
                    pass


if __name__ == '__main__':
    # sort_movies_by_year(SERIES)
    compare_db_and_dir(SERIES, YEAR)
